import sys
import time
import subprocess
import uiautomation as auto


def get_ports():
    screen_width, screen_height = auto.GetScreenSize()
    cmdWindow = auto.GetConsoleWindow()
    if cmdWindow:
        cmdTransformPattern = cmdWindow.GetTransformPattern()
        # cmdTransformPattern.Move(screen_width // 2, 0)
        # cmdTransformPattern.Resize(screen_width // 2, screen_height * 3 //4)
    
    subprocess.Popen('mmc.exe devmgmt.msc')
    mmcWindow = auto.WindowControl(searchDepth=1, ClassName='MMCMainFrame')
    # mmcTransformPattern = mmcWindow.GetTransformPattern()
    # mmcTransformPattern.Move(0, 0)
    # mmcTransformPattern.Resize(screen_width // 2, screen_height * 3 // 4)

    current_ports = []
    tree = mmcWindow.TreeControl()
    for item, depth in auto.WalkControl(tree, includeTop=False):
        if not isinstance(item, auto.TreeItemControl):
            continue
        item.GetSelectionItemPattern().Select(waitTime=0.01)
        pattern = item.GetExpandCollapsePattern()
        if pattern.ExpandCollapseState == auto.ExpandCollapseState.Collapsed:
            pattern.Expand(waitTime=0.01)
        if "COM" in item.Name:  # 检测并存储端口号条目
            current_ports.append(item.Name)
    
    mmcWindow.GetWindowPattern().Close()
    return current_ports


def create_logs(connect_port):
    auto.GetRootControl()
    subprocess.Popen('QXDM.exe')  # 从桌面第一层子控件中找到QXDM程序
    QXDMWindow = auto.WindowControl(searchDepth=1, ClassName='QXDMWindow')
    QXDMWindow.SetTopmost(True)  # 窗口前置

    device_button = QXDMWindow.ButtonControl(searchDepth=3, Name='Connect')
    device_button.Click()
    deviceWindow = auto.WindowControl(searchDepth=3, Name='Device Selection')  # Device Selection窗口
    device_data_item = deviceWindow.DataItemControl(searchDepth=5, Name=connect_port)
    device_data_item.Click()
    device_connect_button = deviceWindow.ButtonControl(searchDepth=4, Name='Connect')
    device_connect_button.Click()

    # auto.GetRootControl()
    # golden_dmc_checkWindow = auto.WindowControl(searchDepth=2, Name='Golden DMC Check')  # 弹出窗口
    # if golden_dmc_checkWindow:
    #     golden_dmc_checkWindow.SetTopmost(True)
    #     yes_button = golden_dmc_checkWindow.ButtonControl(searchDepth=3, Name='Yes')
    #     yes_button.Click()

    device_close_button = deviceWindow.ButtonControl(searchDepth=1, Name='Close')  # 关闭Connect相关窗口
    device_close_button.Click()

    default_button = QXDMWindow.ButtonControl(searchDepth=3, Name='Load Default Configuration')
    default_button.Click()
    defaultWindow = auto.WindowControl(searchDepth=4, Name='Reset Default DMC')  # 加载默认配置
    # defaultWindow.SetTopmost(True)
    yes_button = defaultWindow.ButtonControl(searchDepth=3, Name='Yes')
    yes_button.Click()
    
    time.sleep(1)
    file_bar = QXDMWindow.MenuItemControl(searchDepth=3, Name='File')
    file_bar.Click()
    save_item = QXDMWindow.MenuItemControl(searchDepth=4, Name='Save Items...')
    save_item.Click()
    while not auto.IsKeyPressed(auto.Keys.VK_ENTER):
        continue
    # save_dialog = auto.WindowControl(searchDepth=4, Name='Save Item Store (Cancel To Diacard)?')
    # save_button = save_dialog.ButtonControl(searchDepth=5, Name='保存(S)')
    # save_button.Click()

    device_button.Click()
    deviceWindow = auto.WindowControl(searchDepth=3, Name='Device Selection')  # Device Selection窗口
    device_data_item = deviceWindow.DataItemControl(searchDepth=5, Name=connect_port)
    device_disconnect_button = deviceWindow.ButtonControl(searchDepth=4, Name='Disconnect')
    device_disconnect_button.Click()
    device_close_button.Click()

    # QXDMWindow.ButtonControl(searchDepth=2, Name='关闭').Click()


if __name__ == '__main__':
    # 由于控制台输出更易混淆中英文字符，故对端口号也进行初始化
    connect_port = "Meig HS-USB Diagnostics Port (COM10)"  # 可更换为其他需要确认连接的设备及端口名称
    if auto.IsUserAnAdmin():
        create_logs(connect_port)
        # current_ports = get_ports()
        # print(current_ports)
        # isconnected = False
        # for port in current_ports:
        #     if connect_port in port:
        #         isconnected = True
        #         print("连接成功")
        #         break
        # if isconnected:
        #     create_logs(connect_port)
        # else:
        #     print("请确认端口")
    else:
        print("RunScriptAsAdmin", sys.executable, sys.argv)
        auto.RunScriptAsAdmin(sys.argv)